package com.erp.util;

import java.io.FileOutputStream;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class MailUtil {

	public static void sendEmail() throws Exception {
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");// 发送使用的协议
		props.setProperty("mail.host", "smtp.163.com");// smtp服务器主机地址
		props.setProperty("mail.smtp.auth", "true");// 需要身份验证mail.debug
		props.setProperty("mail.debug", "true");// 调试模式

		Session session = Session.getDefaultInstance(props);
		MimeMessage message = new MimeMessage(session);

		message.setFrom(new InternetAddress("ge_dan_teng@163.com"));
		message.setRecipients(Message.RecipientType.TO, "just_be_fine@163.com");
		message.setSubject("福利你懂得O(∩_∩)O~");

		// ===========文字部分=============
		MimeBodyPart textPart = new MimeBodyPart();
		textPart.setContent("无法直视啊~~~~~<br/><img src='cid:picture' />呵呵呵....",
				"text/html;charset=utf-8");// 设置内容及文本类型

		// ===========图片部分=============
		MimeBodyPart imagePart = new MimeBodyPart();
		// 把磁盘文件读入邮件，借助JAF框架，即activation.jar
		DataHandler dh = new DataHandler(new FileDataSource(
				"C:/Users/dell/Pictures/草泥马.jpg"));
		// 通过JAF框架读取的文件，不需要设置Mime类型，因为JAF会自动识别
		imagePart.setDataHandler(dh);
		imagePart.setContentID("picture");

		// ==========文本与图片合体==========
		MimeMultipart text_image = new MimeMultipart();
		text_image.addBodyPart(textPart);
		text_image.addBodyPart(imagePart);
		text_image.setSubType("related");// 说明两部分的关系

		// ======将文本与图片的合体纳入另一个Body=======
		MimeBodyPart text_imagePart = new MimeBodyPart();
		text_imagePart.setContent(text_image);

		// ===========附件部分=============
		MimeBodyPart attachmentPart = new MimeBodyPart();
		dh = new DataHandler(new FileDataSource(
				"C:/Users/dell/Pictures/11区绅士设计的毛毯.zip"));
		attachmentPart.setDataHandler(dh);
		attachmentPart.setFileName(MimeUtility.encodeText("福利你懂得.zip"));// 手工设置文件名，解决乱码

		// ==========附件与 文本图片的合体 合体==========
		MimeMultipart text_image_attachment = new MimeMultipart();
		text_image_attachment.addBodyPart(text_imagePart);// 文本+图片
		text_image_attachment.addBodyPart(attachmentPart);// 附件
		text_image_attachment.setSubType("mixed");// 说明两部分的关系

		message.setContent(text_image_attachment);
		message.saveChanges();

		message.writeTo(new FileOutputStream("c:/1.eml"));
		Transport ts = session.getTransport();
		ts.connect("ge_dan_teng@163.com", "1139301213Ck");
		ts.sendMessage(message, message.getAllRecipients());
		ts.close();
	}

	public static void main(String[] args) throws Exception {
		sendEmail();
	}

}
